﻿/*
 * @autor: hectorea
 * @date: 01/08/12
 * @project: SortBinaryArray
 */

using System;
using System.Diagnostics;

namespace SortBinaryArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 };

            Stopwatch sw = new Stopwatch();

            sw.Start();
            int[] result = SortBinaryArrayOptimized(a);
            sw.Stop();

            Console.WriteLine("Elapsed time {0} ticks", sw.ElapsedTicks);

            for (int i = 0; i < result.Length; i++)
            {
                Console.Write(" {0} ", result[i]);
            }

            Console.ReadLine();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static int[] SortBinaryArray(int[] input)
        {
            int[] result = new int[input.Length];

            int i = 0;
            int j = input.Length-1;

            int k = input.Length - 1;
            int l = 0;

            while (i<j)
            {
                if (input[i] > input[j])
                {
                    result[k--] = input[i];
                    result[l++] = input[j];
                }
                else if(input[i] < input[j])
                {
                    result[k--] = input[j];
                    result[l++] = input[i];
                }
                else if (input[i] == 0 && input[j] == 0 )
                {
                    result[l++] = input[i];
                    result[l++] = input[j];

                }else if (input[i] == 1 && input[j] == 1 )
                {
                    result[k--] = input[i];
                    result[k--] = input[j];
                }
                i++;
                j--;
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static int[] SortBinaryArrayOptimized(int[] input)
        {
            for (int i = 0; i < input.Length; i++)
            {
                for (int j = i+1; j < input.Length; j++)
                {
                    if (input[i] > input[j])
                    {
                        input[i] ^= input[j];
                        input[j] ^= input[i];
                        input[i] ^= input[j];
                    }
                }
            }

            return input;
        }
    }
}
